package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.handler.YYGHException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-11-11
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        UserInfo userInfo = null;

        //校验数据是否为空
        if (StringUtils.isEmpty(loginVo.getPhone()) || StringUtils.isEmpty(loginVo.getCode())){
            throw new YYGHException(20001,"数据为空");
        }

        //校验验证码
        String redisCode = redisTemplate.opsForValue().get(loginVo.getPhone());
        if (StringUtils.isEmpty(redisCode) || !loginVo.getCode().equals(redisCode)){
            throw new YYGHException(20001,"验证码有误!");
        }


        if (StringUtils.isEmpty(loginVo.getOpenid())){
            //使用手机号登陆
            //校验手机号
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",loginVo.getPhone());
            userInfo = baseMapper.selectOne(queryWrapper);
            if (userInfo == null){
                userInfo = new UserInfo();
                userInfo.setPhone(loginVo.getPhone());
                userInfo.setCreateTime(new Date());
                userInfo.setStatus(1);
                this.save(userInfo);
            }
        }else {
            //使用微信登录
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("openid",loginVo.getOpenid());
            userInfo = baseMapper.selectOne(queryWrapper1);

            QueryWrapper<UserInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("phone",loginVo.getPhone());
            UserInfo userInfo2 = baseMapper.selectOne(queryWrapper2);
            if (userInfo2 == null){
                userInfo.setPhone(loginVo.getPhone());
                baseMapper.updateById(userInfo);
            }else {
                userInfo2.setOpenid(loginVo.getOpenid());
                userInfo2.setNickName(userInfo.getNickName());
                baseMapper.deleteById(userInfo.getId());
                baseMapper.updateById(userInfo2);
                userInfo = userInfo2;
            }
        }

        //查询用户状态
        if (userInfo.getStatus() == 0){
            throw new YYGHException(20001,"该用户已被禁用");
        }

        //显示返回页面中的名字
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (name == null){
            name = userInfo.getNickName();
        }
        if (name == null){
            name = userInfo.getPhone();
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("name",name);
        map.put("token",token);
        return map;
    }

    @Override
    public void userAuth(UserAuthVo userAuthVo, Long userId) {
        //根据id查询用户
        UserInfo userInfo = baseMapper.selectById(userId);
        //保存信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        userInfo.setUpdateTime(new Date());
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> getPageList(Integer page, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus())){
            queryWrapper.eq(UserInfo::getAuthStatus,userInfoQueryVo.getAuthStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getKeyword())){
            queryWrapper.and(t->t.eq(UserInfo::getPhone,userInfoQueryVo.getKeyword()).or().like(UserInfo::getName,userInfoQueryVo.getKeyword()));
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeBegin())){
            queryWrapper.ge(UserInfo::getCreateTime,userInfoQueryVo.getCreateTimeBegin());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd())){
            queryWrapper.le(UserInfo::getCreateTime,userInfoQueryVo.getCreateTimeEnd());
        }
        Page<UserInfo> pageable = new Page<>(page,limit);
        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageable, queryWrapper);
        for (UserInfo record : userInfoPage.getRecords()) {
            this.packUserInfo(record);
        }
        return userInfoPage;
    }

    private void packUserInfo(UserInfo userInfo){
        userInfo.getParam().put("statusString", userInfo.getStatus() == 0 ? "锁定" : "正常");
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = baseMapper.selectById(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String,Object> map = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(id);
        List<Patient> patientList = patientService.getPatientList(id);
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long id, Integer authStatus) {
        UserInfo userInfo = baseMapper.selectById(id);
        userInfo.setAuthStatus(authStatus);
        baseMapper.updateById(userInfo);
    }


}
